<template>
  <j-modal
    :title="title"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :width="700"
    :keyboard="false"
    :forceRender="true"
    @cancel="handleCancel"
    wrapClassName="ant-modal-cust-warp"
    style="top:15%;height: 600px;overflow-y: hidden">
    <template slot="footer">
      <a-button @click="handleCancel">{{$t('inPrint.cancel')}}</a-button>
      <!-- <a-button v-if="isCanCheck" @click="handleOkAndCheck">{{$t('popup.saveReview')}}</a-button> -->
      <a-button type="primary" @click="handleOk" :disabled="confirmLoading">{{$t('commodityManagement.preservation')}}</a-button>
    </template>
    <div style="position:absolute;bottom:53px;right:0;z-index:11" v-if="showRecover && !model.id">
      <span>{{ $t('popup.recoveryPrompt') }}</span>
      <a-button type="link" @click="recover" :disabled="submitBtnDisabled">{{$t('popup.recover')}}</a-button>
      <a-button type="link" @click="lose" :disabled="submitBtnDisabled">{{$t('popup.lose')}}</a-button>
    </div>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row class="form-row" :gutter="24">
          <!-- 选择供应商 -->
          <a-col :lg="12" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('manuManagement.supplier')"
              data-step="1" :data-title="$t('manuManagement.supplier')"
              :data-intro="$t('popup.supplierMustBeSelectedIt')">
              <a-select :placeholder="$t('manuManagement.selectSupplier')" allowClear
                v-decorator="['organId', validatorRules.organId]" :dropdownMatchSelectWidth="false" showSearch
                optionFilterProp="children">
                <div slot="dropdownRender" slot-scope="menu">
                  <v-nodes :vnodes="menu" />
                  <a-divider style="margin: 4px 0;" />
                  <div v-if="isTenant" style="padding: 4px 8px; cursor: pointer;" @mousedown="e => e.preventDefault()"
                    @click="addSupplier"><a-icon type="plus" /> {{ $t('popup.newSupplier') }}</div>
                </div>
                <a-select-option v-for="(item, index) in supList" :key="index" :value="item.id">
                  {{ item.supplier }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="12" :md="24" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('defaultTranslate.operator')">
              <a-input :placeholder="$t('defaultTranslate.operator')" v-decorator="[ 'userName']" :readOnly="true" />
            </a-form-item>
          </a-col>
          
          <a-col :lg="12" :md="24" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator.trim="['creator']" />
            </a-form-item>
          </a-col>
          
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="12" :md="24" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentNo')">
              <a-input :placeholder="$t('setailManagement.pleaseEnterTheDocumentNumber')" v-decorator.trim="[ 'billNo' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="12" :md="24" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentDate')">
              <j-date v-decorator="['billTime', validatorRules.billTime]" :show-time="true" :readOnly="true"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="12" :md="24" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('financialManagement.paymentAccount')"
              data-step="9" :data-title="$t('financialManagement.paymentAccount')"
              :data-intro="$t('popup.ifMultipleAreBox')">
              <a-select style="width:185px;" :placeholder="$t('popup.selectSettlementAccount')"
                v-decorator="['accountId',validatorRules.accountId]" :dropdownMatchSelectWidth="false" allowClear @select="selectAccount" @change="onSelectAccount">
                <div slot="dropdownRender" slot-scope="menu">
                  <v-nodes :vnodes="menu" />
                  <a-divider style="margin: 4px 0;" />
                  <div v-if="isTenant" style="padding: 4px 8px; cursor: pointer;" @mousedown="e => e.preventDefault()"
                    @click="addAccount"><a-icon type="plus" /> {{ $t('popup.newAccount') }}</div>
                </div>
                <a-select-option v-for="(item, index) in accountList" :key="index" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          
          <a-col v-if="showCheckNumber" :lg="12" :md="24" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('financialManagement.checkNumber')">
              <a-input v-decorator.trim="[ 'taxInvoiceNo' ]" :placeholder="$t('financialManagement.pleaseEnterCheckNumber')" />
            </a-form-item>
          </a-col>
          <a-col :lg="12" :md="24" :sm="24"  v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.amountCollected')">
              <a-input :placeholder="$t('financialManagement.pleaseEnterAmountCollected')" v-decorator.trim="[ 'totalPrice' ]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="12" :md="24" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.paymentAmount')">
              <a-input :placeholder="$t('popup.pleasePaymentAmount')" v-decorator.trim="[ 'changeAmount',validatorRules.changeAmount ]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="12" :md="24" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('inPrint.enclosure')">
              <div v-if="fileLoading">Loading...</div>
              <j-upload v-else :fileList="fileList" bizPath="financial"></j-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <person-modal ref="personModalForm" @ok="personModalFormOk"></person-modal>
    <link-bill-list ref="linkBillList" @ok="linkBillListOk"></link-bill-list>
    <account-modal ref="accountModalForm" @ok="accountModalFormOk"></account-modal>

  </j-modal>
</template>
<script>
  import pick from 'lodash.pick'
  import { findBySelectCus, findBySelectSup,getAccount } from '@/api/api'
  
import AccountModal from '@/views/system/modules/AccountModal'
  import PersonModal from '@/views/system/modules/PersonModal'
  import { FormTypes } from '@/utils/JEditableTableUtil'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
  import { FinancialModalMixin } from '../mixins/FinancialModalMixin'
  import JUpload from '@/components/jeecg/JUpload'
  import JDate from '@/components/jeecg/JDate'
  import LinkBillList from '@/views/bill/dialog/LinkBillList'
  export default {
    name: "AdvanceReceivedModel",
    mixins: [JEditableTableMixin, FinancialModalMixin],
    components: {
      PersonModal,
      JUpload,
      JDate,
      LinkBillList,
      AccountModal,
      VNodes: {
        functional: true,
        render: (h, ctx) => ctx.props.vnodes,
      }
    },
    data () {
      return {
        title:this.$t('setailManagement.operation'),
        width: '800',
        moreStatus: false,
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        visible: false,
        model: {},
        fileList:[],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        refKeys: ['accountDataTable', ],
        activeKey: 'accountDataTable',
        accountTable:{
          loading:false
        },
        showCheckNumber:false,
        confirmLoading: false,
        validatorRules:{
          organId:{
            rules: [
              { required: true, message: this.$t('popup.pleasePaymentMember')+'!' }
            ]
          },
          handsPersonId:{
            rules: [
              { required: true, message:this.$t('popup.pleaseSelectPersonnel')+'!'}
            ]
          },
          billTime:{
            rules: [
              { required: true, message: this.$t('popup.pleaseSelectDocumentDate')+'!' }
            ]
          },
          accountId: {
            rules: [
              { required: true, message: this.$t('financialManagement.paymentAccount') + '!' }
            ]
          },
          changeAmount: {
            rules: [
              { required: true,validator:this.validateNumber, message: this.$t('otherJS.greaterThan0') + '!' }
            ]
          },
            
        },
        prefixNo: 'TQFK',
        url: {
          add: '/accountHead/addAccountHeadAndDetail',
          edit: '/accountHead/updateAccountHeadAndDetail',
          detailList: '/accountItem/getDetailList'
        }
      }
    },
    created () {
    },
    methods: {
      validateNumber(rule, value, callback){
        if(+value<=0){
          callback(false,'金额必须大于0')
        }
        callback()
      },
      selectAccount (value) {
      if (value === 0) {
        //多账户
        this.$refs.manyAccountModalForm.edit(this.accountIdList, this.accountMoneyList)
        this.$refs.manyAccountModalForm.title = '多账户结算'
        this.manyAccountBtnStatus = true
      } else {
        this.accountIdList = []
        this.accountMoneyList = []
        this.manyAccountBtnStatus = false
      }
    },
    onSelectAccount (value) {
      const item = this.accountList.find(item => item.id === value)
      const IS_CHECK_PAY = '1'
      if (value && item.type && item.type.toString() === IS_CHECK_PAY) {
        this.showCheckNumber = true
      } else {
        this.showCheckNumber = false
      }
    },
      //调用完edit()方法之后会自动调用此方法
      editAfter() {
        this.billStatus = '0'
        if (this.action === 'add') {
          this.addInit(this.prefixNo)
          this.fileList = []
        } else {
          this.model.billTime = this.model.billTimeStr
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.model,'organId', 'handsPersonId', 'billTime', 'billNo', 'remark','accountId','creator','userName',
                  'totalPrice', 'changeAmount'))
          });
          
          // 加载子表数据
          let params = {
            headerId: this.model.id
          }
          let url = this.readOnly ? this.url.detailList : this.url.detailList;
          this.requestSubTableData(url, params, this.accountTable);
        }
        this.initSupplier()
        this.initAccount()
      },
      initSupplier() {
        let that = this;
        findBySelectSup({}).then((res)=>{
          if(res) {
            that.supList = res;
          }
        });
      },
      onSearchLinkNumber() {
      let organId = this.form.getFieldValue('organId')
      // this.$refs.linkBillList.show('其它', this.$t('manuManagement.purchaseOrder'), this.$t('warehouseManagement.supplier'), "1,3", organId)
      this.$refs.linkBillList.acceptanceShow('其它', '厂家直发', this.$t('manuManagement.customer'), "1,2,3", organId, this.prefixNo)
      this.$refs.linkBillList.title = this.$t('manuManagement.directOrdersFromManufacturers')
    },
    addAccount () {
      this.$refs.accountModalForm.add()
      this.$refs.accountModalForm.title = '新增收款账户'
      this.$refs.accountModalForm.disableSubmit = false
    },
    initAccount () {
      let that = this
      getAccount({}).then(res => {
        if (res && res.code === 200) {
          let list = res.data.accountList
          that.accountList = list
        }
      })
    },
    linkBillListOk(selectBillDetailRows) {
      this.rowCanEdit = false
      if(selectBillDetailRows && selectBillDetailRows.length>0) {
        this.$nextTick(() => {
          this.form.setFieldsValue({
            'number': selectBillDetailRows[0].number
          })
        })
        this.accountTable.dataSource = selectBillDetailRows;
        let totalPrice = 0
        selectBillDetailRows.forEach(item => {
          item.eachAmount = item.totalPrice
          totalPrice = this.__addition(Number(item.totalPrice), totalPrice)
        })
        this.$nextTick(() => {
          this.form.setFieldsValue({
            totalPrice: totalPrice,
            changeAmount: totalPrice,
            organId: selectBillDetailRows[0].organId
          })
        })
      }
    },
    onChange ({row, target}) {
      target.getValues((err, values) => {
        const total = values.reduce((pre, cur) => {
          return this.__addition(pre, Number(cur.eachAmount))
        }, 0)
        this.form.setFieldsValue({
          changeAmount: total,
          totalPrice: total
        })
      }, true)
    },
      //提交单据时整理成formData
      classifyIntoFormData(values) {
        let billMain = Object.assign({},values)
        billMain.type = '预付款'
        billMain.changeAmount = -billMain.changeAmount
        billMain.totalPrice = billMain.changeAmount
        if(this.model.id){
          billMain.id = this.model.id
        }
        let fileList = JSON.stringify(JSON.parse(localStorage.getItem("fileList")))
        return {
          info: JSON.stringify(billMain),
          attachment: fileList,
          rows: null,
        }
      },
      handleOk(){
        this.form.validateFields((err, values) => {
          if (!err) {
            console.log('values :>> ', values);
            let formData = this.classifyIntoFormData(values)
            formData.passDirect = true
          formData.functionId = this.$route.meta.id
            this.request(formData)
          }
        })
      },
      removeRows (text) {
        this.$refs[this.refKeys[0]].removeRows(text.rowId)
      }
    }
  }
</script>
<style scoped lang="less">
::v-deep .ant-spin-container .thead {
  background: #beddf9;
  & > .tr > .td {
    border-left: 1px solid #f2f2f2;
    text-align: center;
  }
}
</style>